from datetime import datetime

from applications.configs.func import verify_password
from applications.middlewares.JWT import create_jwt_token
from applications.models import Session
from applications.models.users import Users


def login(data):
    session = Session()
    user = session.query(Users).filter_by(username=data.username).first()
    if not user:
        return False, "没有该用户信息"
    # 验证密码
    if not verify_password(data.password, user.password):
        return False, "用户密码有误"
    # 修改最后登录时间
    session.query(Users).filter_by(username=data.username).update({"last_use": datetime.now()})
    # 生成token
    token = create_jwt_token({"id": user.id, "Domain": "web"})
    session.close()
    return True, {"username": user.username, "token": token}